package dao

import (
	"context"
	"device-admin/internal/dal"
	"device-admin/internal/models"
	"time"

	"192.168.1.75/go-pkg/errorx"
)

type TerminalScreencapLog struct{}

// Add 新增截图日志
func (TerminalScreencapLog) Add(
	ctx context.Context,
	query *dal.Query,
	robotID, terminalType string,
	screencapName string, // 截图名称
	userID string, // 用户id
) error {
	tsl := dal.TerminalScreencapLog
	err := tsl.WithContext(ctx).Create(&models.TerminalScreencapLog{
		UserID:        userID,
		RobotID:       robotID,
		TerminalType:  terminalType,
		ScreencapName: screencapName,
	})
	if err != nil {
		return errorx.New(err.Error(), -2)
	}
	return nil
}

// List 截图日志列表
func (TerminalScreencapLog) List(
	ctx context.Context,
	query *dal.Query,
	robotID, terminalType string,
	page, limit int, // 分页信息
) (records []*models.TerminalScreencapLog, total int64, err error) {
	tsl := dal.TerminalScreencapLog
	tx := tsl.WithContext(ctx).
		Where(tsl.RobotID.Eq(robotID)).
		Where(tsl.TerminalType.Eq(terminalType))
	// 总数
	total, _ = tx.Count()
	// 记录
	records, err = tx.
		Select(
			tsl.ID,
			tsl.ScreencapName,
			tsl.CreatedAt,
			tsl.UserID,
		).
		Order(tsl.CreatedAt.Desc()).
		Offset(GetPageOffset(page, limit)).
		Limit(GetPageLimit(limit)).
		Find()
	if err != nil {
		return []*models.TerminalScreencapLog{}, total, errorx.New(err.Error(), -2)
	}
	// 加上路由前缀
	for index, record := range records {
		records[index].ScreencapName = "/device-admin/be-file/screencap/" + robotID + "/" + record.ScreencapName
	}
	return records, total, nil
}

// DelExpired 删除过期的截屏，默认仅保存72小时
func (TerminalScreencapLog) DelExpired(
	ctx context.Context,
	query *dal.Query,
	robotID, terminalType string,
) {
	tsl := dal.TerminalScreencapLog
	tx := tsl.WithContext(ctx)
	// 只保存三天
	tx = tx.Where(tsl.CreatedAt.Lt(time.Now().Unix() - 3600*24*3))
	if robotID != "" {
		tx.Where(tsl.RobotID.Eq(robotID))
	}
	if terminalType != "" {
		tx.Where(tsl.TerminalType.Eq(terminalType))
	}
	tx.Delete()
}
